const Router = require('koa-router')
const AddressModel = require('../models/address')

const route = new Router({ prefix: '/api/address' })

// 曾

/*
    "_id": "5ff45a0e6f9fe52d80ffe938"
    "openid": "321 - 100", 
    "name": "321 321 - 100", 
    "phone": "321 321 - 100", 
    "province": "321", 
    "detail": "321", 
    "postcod": "321", 
*/

route.put('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {}
    }
    const { 
        openid, name, phone, province, detail, postcode,
     } = ctx.request.body
    try {
        res.data = await AddressModel.create({
            openid, name, phone, province, detail, postcode,
        })
        res.success = true
    } catch (error) {
        ctx.status = 500
        res.error = error.message
    }
    ctx.body = res
})

// 删
route.delete('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {}
    }
    try {
        const { id } = ctx.query
        let address = await AddressModel.findById(id)
        address.set({
            isDelete: true
        })
        await address.save()
        res.success = true
    } catch (error) {
        res.error = error.message
        ctx.status = 500
    }
    ctx.body = res
})
// 改
route.post('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {}
    }
    try {
        const { 
            openid, name, phone, province, detail, postcode,
            _id
        } = ctx.request.body
        let address = await AddressModel.findById(_id)
        address.set({
            openid, name, phone, province, detail, postcode,
        })
        await address.save()
        res.success = true
    } catch (error) {
        res.error = error.message
        ctx.status = 500
    }
    ctx.body = res
})
// 查
route.get('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {}
    }
    const { openid } = ctx.query
    try {
        res.data = await AddressModel.find({ openid, isDelete: false })
        res.success = true
    } catch (error) {
        ctx.status = 500
        res.error = error.message
    }
    ctx.body = res
})
module.exports = route
